clear all;

%% construct data

cd ..; cd ..; cd ..; cd ..; 
load('code_main_model\6_implied_w_r\computation_results\data.mat','d','nmkt','Pi','Z');
load('code_main_model\6_implied_w_r\input\comm_loc_model.mat','comm_loc_model');
cd 'code_figure_table\maintext\Table 2\model';

data(1:nmkt,1:10)=0;
data(:,1)=1:1:nmkt;
data(:,2)=Pi;
data(:,3)=Z;
data(:,4)=d(1,:)';
data(:,5)=d(3,:)';
data(:,6)=d(5,:)';
data(:,7)=d(7,:)';
data(:,8)=d(9,:)';
data(:,9)=d(11,:)';

bank86=find(d(1,:)==0);
data(bank86,:)=[];

control=find(comm_loc_model(:,11)==0);

%% matching
control_already_matched=[];

loc_88=find(comm_loc_model(:,1)==0 & comm_loc_model(:,3)~=0);
cov_index=[2,3,4];
[matched88, beta88, t88]=PSM(loc_88, control, control_already_matched, data, cov_index);
control_already_matched=[control_already_matched; control(ismember(control,matched88(:,2)))];

loc_90=find(comm_loc_model(:,3)==0 & comm_loc_model(:,5)~=0);
cov_index=[2,3,5];
[matched90, beta90, t90]=PSM(loc_90, control, control_already_matched, data, cov_index);
control_already_matched=[control_already_matched; control(ismember(control,matched90(:,2)))];

loc_92=find(comm_loc_model(:,5)==0 & comm_loc_model(:,7)~=0);
cov_index=[2,3,6];
[matched92, beta92, t92]=PSM(loc_92, control, control_already_matched, data, cov_index);
control_already_matched=[control_already_matched; control(ismember(control,matched92(:,2)))];

loc_94=find(comm_loc_model(:,7)==0 & comm_loc_model(:,9)~=0);
cov_index=[2,3,7];
[matched94, beta94, t94]=PSM(loc_94, control, control_already_matched, data, cov_index);
control_already_matched=[control_already_matched; control(ismember(control,matched94(:,2)))];

loc_96=find(comm_loc_model(:,9)==0 & comm_loc_model(:,11)~=0);
cov_index=[2,3,8];
[matched96, beta96, t96]=PSM(loc_96, control, control_already_matched, data, cov_index);
control_already_matched=[control_already_matched; control(ismember(control,matched96(:,2)))];

matched=[matched88;matched90;matched92;matched94;matched96];

treatmkt=matched(:,1);
controlmkt=matched(:,2);

save('DID_a_matching.mat','treatmkt','controlmkt')